import './add.less';
import Panel from "./../../elements/Panel";
import Header from "./../../components/Header";
import Modal from "./../../components/Modal/";
import {connect} from "react-redux";
import CONFIG from "./../../libs/config";
import {Lang, Fetch, Fetch_} from "./../../libs/";
import {URL, md5Url} from "./../../libs/Url";
import Label from "./../../components/FormLabel";
import FormGroup from "./../../components/FormGroup";
import FormItem from "./../../components/FormItem";
import FormItemRef from "./../../components/FormItemRef";
import Lesson from "./../../components/form/lesson";
import FormItemType from "./../../components/FormItemType";
import InputGroup from "./../../components/InputGroup";
import Selected from "./../../components/SelectItem";
import {Warn} from "./../../components/alert/";
import BreadcrumbNavigation from "./../../components/BreadcrumbNavigation";
import SingleSelectClass from "./../../components/form/single_select_class";
import {fetch, fetchUser} from "../../actions";
import {SUBJECT, PAGE_SUBJECT} from "./../../actions/subject";


const AddTeachSchedule = React.createClass({
    getInitialState(){
        const self = this;
        this.isUpdate = this.props.router.params.id;
        let form = [
            {
                label: '科目',
                value: '',
                type: FormItemType.TEXT_SHOW,
            },
            {
                label: '教师',
                value: '',
                type: FormItemType.TEXT_SHOW,
            },
            {
                name: 'teachids',
                label: '推送班级',
                value: '',
                required: true,
                tips: '',
                type: FormItemType.MODAL_CHECK_BOX,
            },
            {
                name: 'name',
                label: '标题',
                placeholder: '',
                required: true, // 必填、默认进行非空校验
                // verify: [{
                //     regex: /a/, //验证规则
                //     tips: '' // 错误提示
                // }],
                value: '',
                tips: '',
                type: FormItemType.INPUT,
            },
            {
                name: 'analysis',
                label: '学情分析',
                required: false,
                value: '',
                placeholder: '',
                tips: '',
            },
            {
                name: 'target',
                label: '教学目标',
                required: false,
                value: '',
                placeholder: '',
                tips: '',
            },
            {
                name: 'keypoint',
                label: '重点难点',
                required: false,
                value: '',
                placeholder: '',
                tips: '',
            },
            {
                name: 'comment',
                label: '备注',
                value: '',
                placeholder: '',
                tips: '',
            },

        ];

        return {
            open: false,
            selected: '',
            pageState: false,
            form: form,
            tmpForm: [],//表单缓存变量
            tmp: {
                push_class: ''
            },
            schedules: {},
            schedule_lesson: [],
            teachingPlanId: '',
            tips: {}
        }
    },
    setchange(index, content){
        const self = this;
        self.setState({
            form: [
                ...self.state.form.slice(0, index),
                Object.assign({}, self.state.form[index], {
                    value: content,
                    tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                }),
                ...self.state.form.slice(index + 1),
            ]
        })
    },
    componentDidMount() {
        const {dispatch, user} = this.props, self = this;
        if (this.isUpdate) {
            Promise.all([
                Fetch(URL.TEACH_SCHEDULE_GET,
                    {
                        body: {teachingid: this.isUpdate}
                    }),
                Fetch(URL.TEACH_SCHEDULE_FIND_ITEM,
                    {
                        body: {teachingid: this.isUpdate}
                    })
            ])
                .then(res=> {
                    var course = (res[1].coureses);
                    var tp = res[0].teachingplan;

                    var form = [
                        ...this.state.form.slice(0, 2),
                        Object.assign({}, this.state.form[2], {
                            value: res[0]['class'].map((itemc, indexc)=> {
                                return itemc.teachid
                            }).toString()
                        }),
                        Object.assign({}, this.state.form[3], {
                            value: tp.name
                        }),
                        Object.assign({}, this.state.form[4], {
                            value: tp.analysis
                        }),
                        Object.assign({}, this.state.form[5], {
                            value: tp.target
                        }),
                        Object.assign({}, this.state.form[6], {
                            value: tp.keypoint
                        }),
                        Object.assign({}, this.state.form[7], {
                            value: tp.comment
                        }),
                        ...this.state.form.slice(7),
                    ];
                    var schedule_lesson = Object.keys(course).map((item, index)=> {
                        item = course[item];
                        return {
                            name: item.courseInfo.name,
                            comment: item.courseInfo.comment,
                            fileids: item.courseInfo.fileids,
                            courseid: item.courseInfo.id,
                            courseList: item.classInfo.map((item_, index)=> {
                                return {
                                    class_: {
                                        'class': item_
                                    },
                                    teachid: self.isUpdate,
                                    time: item_.time
                                }
                            })
                        };
                    })
                    self.setState({
                        form: form,
                        schedule_lesson: schedule_lesson
                    })
                })
                .catch(e=> {
                    console.log(e)
                })
        }
        dispatch(fetchUser(SUBJECT.NEWS_CATEGORY));
        dispatch(fetch({url: URL.CATEGORY_FIND}));
        if (user['class'] instanceof Array) {
            var schedules = [];

            user['class'].forEach(item=> {
                schedules.push(Fetch_(URL.SCHEDULE_GET, {body: {classid: item.classid}}))
            });

            Promise.all(schedules)
                .then(res=> {
                    var schedule = {};
                    res.slice(0, user['class'].length).forEach((item, index)=> {
                        schedule[user['class'][index].classid] = Object.assign({}, {
                            list: item.list,
                            classInfo: user['class'][index]
                        }, {
                            selected: {},
                            tmp: {},
                        });
                    });
                    // var last = res[res.length - 1].homework;
                    self.setState({
                        schedules: schedule
                    });
                })
                .catch(e=> {
                    console.log(e);
                })
        }
    },

    cloneArray(arr){
        var self = this;
        return arr.map(item=> {
            return self.deepClone(item);
        });
    },
    deepClone(obj) {
        var self = this;
        var o = obj instanceof Array ? [] : {};
        for (var k in obj)
            o[k] = typeof obj[k] === Object ? self.deepClone(obj[k]) : obj[k];
        return o;
    },
    componentWillReceiveProps(nextProps){

        const {dispatch, user} = this.props, self = this;
        if (typeof nextProps.user == 'object') {
            let subjectName = nextProps.user.teacher ? nextProps.user.teacher.subject.name : '';
            let teacherName = nextProps.user.name;
            this.setState({
                form: [
                    Object.assign({}, this.state.form[0], {value: subjectName}),
                    Object.assign({}, this.state.form[1], {value: teacherName}),
                    ...this.state.form.slice(2)
                ],
                user: nextProps.user
            })
        }
    },
    /***
     * 缓存选中班级
     */
    saveSelectedClass(ids){
        let class_tmp = [];
        this.state.user['class'].forEach((item)=> {
            if (ids.indexOf(item.teachid) > -1) {
                class_tmp.push(item);
            }
        });
        this.setState({
            user: Object.assign({}, this.state.user, {
                ['selected_class']: class_tmp
            })
        })
    },
    onsubmit(data){
        const self = this;
        const tmp = self.cloneArray(data);
        let form_ = {};
        data.forEach((item)=> {
            item.name && (form_[item.name] = item.value);
        });
        form_.teachids = form_.teachids.substring(0, form_.teachids.length - 1);
        self.saveSelectedClass(form_.teachids);//缓存选中班级数据
        if (this.state.editing == undefined) {
            Fetch(this.isUpdate ? URL.TEACH_SCHEDULE_MODIFY : URL.TEACH_SCHEDULE_ADD_SUMMARY,
                {
                    body: Object.assign({},
                        form_,
                        this.isUpdate ? {teachingid: this.isUpdate} : {})
                })
                .then(res=> {
                    var c = {
                        tmpForm: tmp,
                        teachingPlanId: res.teachingPlan.id,//新建教学计划ID
                        form: data.map(item=> {
                            item.type = FormItemType.TEXT_SHOW;
                            return item;
                        }),
                        pageState: true,
                        editing: true
                    };
                    self.setState(c);
                })
                .catch(e=> {
                    console.log(e.stack);
                });
        } else if (this.state.editing) {
            // form_.teachingid = this.state.teachingPlanId;
            // if(){
            var tmpForm = self.cloneArray(self.state.tmpForm);
            var c = {
                tmpForm: tmp,
                teachingPlanId: this.state.teachingPlanId,//新建教学计划ID
                form: data.map((item, index)=> {
                    item.type = tmpForm[index].type;
                    return item;
                }),
                pageState: true,
                editing: false
            };
            self.setState(c);
            // }

        } else if (this.state.editing == false) {
            form_.teachingid = this.state.teachingPlanId;
            Fetch(URL.TEACH_SCHEDULE_MODIFY,
                {
                    body: form_
                })
                .then(res=> {
                    var c = {
                        tmpForm: tmp,
                        teachingPlanId: this.state.teachingPlanId,//新建教学计划ID
                        form: data.map((item, index)=> {
                            item.type = FormItemType.TEXT_SHOW;
                            return item;
                        }),
                        pageState: true,
                        editing: true
                    };
                    self.setState(c);
                })
                .catch(e=> {
                    console.log(e.stack);
                });
        }

    },
    onEditing(){

    },
    render(){
        const self = this;
        const {user, dispatch}  = this.props;
        //const form = this.props[PAGE_SUBJECT.NEWS_ADD].form;
        const data_category = self.props[md5Url.CATEGORY_FIND] || {};
        (!data_category.list && (data_category.list = []));
        console.log(this.state.schedule_lesson);
        var user_ = (this.state.user && this.state.user['class'] instanceof Array) ? this.state.user : {"class": []};
        return (
            <div>
                <BreadcrumbNavigation navs={[
                    {url: CONFIG.MENUS.HOME, label: Lang.menus.HOME},
                    {url: CONFIG.MENUS.TEACH_SCHEDULE, label: Lang.menus.TEACH_SCHEDULE},
                    {label: this.isUpdate ? Lang.menus.TEACH_SCHEDULE_UPDATE : Lang.menus.TEACH_SCHEDULE_ADD},
                ]}>
                </BreadcrumbNavigation>
                <Panel>
                    <Header>{this.isUpdate ? Lang.menus.TEACH_SCHEDULE_UPDATE : Lang.menus.TEACH_SCHEDULE_ADD}</Header>
                    <Warn>
                        <strong>说明：</strong>1、添加本学期的教学计划总纲； 2.保存成功后，可进行课时安排的添加；
                    </Warn>
                    <h5 className="add-h5">教学计划总纲</h5>
                    <div className="form-horizontal">
                        <FormItemRef
                            _user={user_} //登录用户信息，非必传
                            form={this.state.form}
                            editing={this.state.editing}

                            onsubmit={(data)=> {
                                self.onsubmit(data)
                            }}
                        />
                    </div>
                    {
                        (self.state.pageState || self.isUpdate) ? <div>
                            <h5 className="add-h5">课时安排</h5>
                            <div className="lessonPlan">
                                {
                                    this.state.schedule_lesson.map((item, index_)=> {
                                        return <dl key={index_}>
                                            <dt>{index_ + 1}、{item.name}
                                                <span>
                                                    <a className="btn btn-default btn-xs">
                                                        <i
                                                            onClick={()=> {
                                                                self.setState({
                                                                    open: true,
                                                                    selected: '',
                                                                    status: 'update',
                                                                    item: item
                                                                })
                                                            }}
                                                            className="fa fa-pencil"></i>
                                                    </a>
                                                    <button
                                                        className="btn btn-default btn-xs"
                                                        onClick={()=> {
                                                            Fetch_(URL.TEACH_SCHEDULE_DELETE_ITEM, {
                                                                body: {
                                                                    courseid: item.courseid
                                                                }
                                                            }).then(res=> {
                                                                self.setState({
                                                                    schedule_lesson: [
                                                                        ...this.state.schedule_lesson.slice(0, index_),
                                                                        ...this.state.schedule_lesson.slice(index_ + 1),
                                                                    ]
                                                                })
                                                            }).catch(e=> {
                                                                console.log(e);
                                                            })
                                                        }}
                                                    >
                                                        <i className="fa fa-times"></i>
                                                    </button>
                                                </span>
                                                <i className="open fa fa-angle-down"></i>
                                            </dt>
                                            {item.courseList.map((itemc, indexc)=> {
                                                return <dd key={indexc}>
                                                    <b>{itemc.class_['class'].name}</b>
                                                    <span>
                                                    <i>推送时间：</i>
                                                        {itemc.time || '未设置推送时间'}
                                                </span>
                                                </dd>
                                            })}

                                        </dl>
                                    })
                                }
                                <br/>
                                <div className="row table-list-head">
                                    <div className="col-md-6">
                                        <a style={{marginLeft: '50px'}}
                                           onClick={()=> {
                                               self.setState({open: true, selected: '', status: 'add',})
                                           }}
                                           className="btn btn-primary btn-sm">
                                            <i className="fa fa-plus"> 新建课时计划</i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <Modal
                                className="modal-lg"
                                open={self.state.open}>
                                <Modal.Header
                                    onclose={()=> {
                                        self.setState({open: false, selected: ''})
                                    }
                                    }>
                                    {Lang.NEWS_CREATE.choose}
                                </Modal.Header>
                                <Modal.Body>
                                    <Lesson
                                        onconfirm={(data)=> {
                                            data.teachingid = self.state.teachingPlanId;
                                            if (this.isUpdate)data.teachingid = this.isUpdate;
                                            Fetch(self.state.status == 'add' ? URL.TEACH_SCHEDULE_ADD_ITEM : URL.TEACH_SCHEDULE_UPDATE_ITEM, {
                                                method: 'POST',
                                                body: data,
                                            })
                                                .then(res=> {
                                                    if (data.courseid) {
                                                        self.state.schedule_lesson.forEach((item, index)=> {
                                                            if (item.courseid == data.courseid) {
                                                                data.index = index;
                                                            }
                                                        });
                                                        self.setState({
                                                            schedule_lesson: [
                                                                ...self.state.schedule_lesson.slice(0, data.index),
                                                                data,
                                                                ...self.state.schedule_lesson.slice(data.index + 1)
                                                            ]
                                                        });
                                                        self.setState({open: false, selected: ''})
                                                    } else {
                                                        data.courseid = res.courseInfoPO.courseid;
                                                        self.setState({
                                                            schedule_lesson: [...self.state.schedule_lesson, data]
                                                        });
                                                        self.setState({open: false, selected: ''})
                                                    }

                                                })
                                                .catch(e=> {
                                                    console.log(e);
                                                });

                                        }}
                                        status={self.state.status}
                                        item={self.state.item}
                                        schedules={self.state.schedules}
                                        user={self.state.user}
                                    />
                                </Modal.Body>
                            </Modal>
                        </div> : ''
                    }

                </Panel>
            </div>
        )
    }
});
function select(state) {
    return {
        user: state.user.user,
        [md5Url.CATEGORY_FIND]: state.fetchBySubject[md5Url.CATEGORY_FIND],
        [md5Url.NEWS_ADD]: state.fetchBySubject[md5Url.NEWS_ADD],
        [PAGE_SUBJECT.NEWS_ADD]: state.pageBySubject[PAGE_SUBJECT.NEWS_ADD]
    }
}
export default connect(select)(AddTeachSchedule)